package com.tony.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import okhttp3.*;

import javax.net.ssl.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    public static HttpUtil instance;
    private boolean isDev;
    private boolean isAgent;


    public static HttpUtil getInstance(boolean isDev,boolean isAgent){
        if(instance==null){
            instance=new HttpUtil();
        }
        instance.setAgent(isAgent);
        instance.setDev(isDev);
        return instance;
    }


    private OkHttpClient init(){
        OkHttpClient client = null;
        try{
            SSLSocketFactory sslSocketFactory1 = null;
            X509TrustManager trustManager = new MyX509TrustManager();
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new MyX509TrustManager[] { (MyX509TrustManager) trustManager }, null);
            sslSocketFactory1 = sslContext.getSocketFactory();

            OkHttpClient.Builder builder=new OkHttpClient().newBuilder();
            builder .connectTimeout(60, TimeUnit.SECONDS)
                    .followRedirects(false)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS);

            if(isDev){
                if(isAgent){
                    String ip="127.0.0.1";
                    int port=8888;

                    JSONObject jsonObject= getIpAndPort();
                    if(jsonObject!=null){
                        ip=jsonObject.getString("ip");
                        port=Integer.parseInt(jsonObject.getString("port"));
                    }

                    if(port==8888){
                        System.out.println("代理获取异常！！不使用代理");
                    }else{
                        builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port)));
                    }

                }else{
                    builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)));
                }
            }

            client=builder.sslSocketFactory(sslSocketFactory1).hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            }).build();

        }catch (Exception e){
            //e.printStackTrace();
            System.err.println("okhttp error");
        }

        return client;
    }

    public String sendGet(String url,Map<String,String> headerMap){
        String result="";
        try{
            OkHttpClient client=init();
            Request.Builder builder = new Request.Builder();
            builder.url(url);

            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }

            Request request=builder.build();
            Response response = client.newCall(request).execute();
            result= response.body().string();
        }catch (Exception e){
            //e.printStackTrace();
            System.err.println("get request error");
        }
        return result;
    }

    public String sendGetHeader(String url,Map<String,String> headerMap,int code,String key){
        String result="";
        try{
            OkHttpClient client=init();
            Request.Builder builder = new Request.Builder();
            builder.url(url);

            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }

            Request request=builder.build();
            Response response = client.newCall(request).execute();
            if(response.code()==code){
                result=response.header(key);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public byte[] sendGetByte(String url,Map<String,String> headerMap){
        byte[] result = new byte[0];
        try{
            OkHttpClient client=init();
            Request.Builder builder = new Request.Builder();
            builder.url(url);

            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }

            Request request=builder.build();
            Response response = client.newCall(request).execute();
            result= response.body().bytes();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    public String sendPost(String url, Map<String,String> headerMap, RequestBody body){
        String result="";
        try{
            OkHttpClient client=init();
            Request.Builder builder = new Request.Builder();
            builder.url(url);

            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }

            builder.post(body);
            Request request=builder.build();
            Response response = client.newCall(request).execute();
            result= response.body().string();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    public String sendPost(String url,Map<String,String> headerMap,String data){
        String result="";
        try{
            OkHttpClient client=init();
            Request.Builder builder = new Request.Builder();
            builder.url(url);

            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }

            if(!TextUtil.isEmpty(data)){
                MediaType type = MediaType.parse(headerMap.get("Content-Type"));
                RequestBody body = RequestBody.create(type, data);
                builder.post(body);
            }

            Request request=builder.build();
            Response response = client.newCall(request).execute();
            result= response.body().string();
        }catch (Exception e){
            //e.printStackTrace();
            System.err.println("post request error");
        }
        return result;
    }


    public byte[] sendPostByte(String url,Map<String,String> headerMap,String data){
        byte[] result=new byte[0];
        try{
            OkHttpClient client=init();
            Request.Builder builder = new Request.Builder();
            builder.url(url);

            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }

            if(!TextUtil.isEmpty(data)){
                MediaType type = MediaType.parse(headerMap.get("Content-Type"));
                RequestBody body = RequestBody.create(type, data);
                builder.post(body);
            }

            Request request=builder.build();
            Response response = client.newCall(request).execute();
            result= response.body().bytes();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    //蘑菇代理
    private JSONObject getIpAndPort(){
        String url="http://piping.mogumiao.com/proxy/api/get_ip_al?appKey=817dfbb599944526a7190a2f45ab8a92&count=1&expiryDate=0&format=1&newLine=2";
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            System.out.println(result);
            if(!TextUtil.isEmpty(result)){
                JSONObject jsonObject=JSONObject.fromObject(result);
                if(jsonObject!=null&&jsonObject.has("msg")&&jsonObject.has("code")&&jsonObject.getInt("code")==0){
                    JSONArray jsonArray=jsonObject.getJSONArray("msg");
                    if(jsonArray!=null&&jsonArray.size()>0){
                        return jsonArray.getJSONObject(0);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }





    public boolean isDev() {
        return isDev;
    }

    public void setDev(boolean dev) {
        isDev = dev;
    }

    public boolean isAgent() {
        return isAgent;
    }

    public void setAgent(boolean agent) {
        isAgent = agent;
    }
}

